<template>
  <el-upload class="avatar-uploader" action="api/file/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="src" :src="src" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { ref, defineModel } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const src = defineModel()
// const imageUrl = ref('')
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 200) {
    src.value = response.data
    ElMessage.success(response.msg)
  } else {
    ElMessage.error(response.msg)
  }
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    return ElMessage.error('上传头像必须图片格式')
  } else if (rawFile.size / 1024 / 1024 > 10) {
    return ElMessage.error('文件超出10MB!')
  }
  return true
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
